--编辑场景


require "app.models.Common"
require "app.models.CollideManager"
local Block = require "app.models.Block"
local Fence = require "app.models.Fence"
local BlockFactory = require "app.models.BlockFactory"


local EditorScene = class("EditorScene", cc.load("mvc").ViewBase)

function EditorScene:onCreate()
    self.fence = Fence.new(cBound, self)
    self.curX, self.curY, self.curIndex = 0, 0, 0
    self:SwitchCusor(1)
    self:ProcessInput()
    self.blockFactory = BlockFactory.new(self)
    print(package.path)
end

local  cMaxBlock = 3
function EditorScene:SwitchCusor(delta)
    if nil == self.cur then
        self.cur = Block.new(self)
    end

    local newIndex = self.curIndex + delta
    newIndex = math.max(newIndex, 1)
    newIndex = math.min(newIndex, cMaxBlock)

    self.curIndex = newIndex
    self.cur:Set(newIndex)
    self.cur:SetPos(self.curX, self.curY)
end

function EditorScene:MoveCusor(deltaX, deltaY)
   self.cur:SetPos(self.curX + deltaX, self.curY + deltaY)
   self.curX, self.curY = self.cur.x, self.cur.y
end

function EditorScene:ProcessInput()
   local function keyboardProcess( keycode, event )
        if 28 == keycode then   --键盘光标up键
            print("键盘光标up键")
            self:MoveCusor(0, 1)
        elseif 29 == keycode then   --键盘光标down键
            print("键盘光标down键")
            self:MoveCusor(0, -1)
        elseif 26 == keycode then   --键盘光标left键 
            self:MoveCusor(-1, 0)
        elseif 27 == keycode then   --键盘光标right键  
            self:MoveCusor(1, 0)
        elseif 38 == keycode then   --page up    
            self:SwitchCusor(1)
        elseif 44 == keycode then   --page down
            self:SwitchCusor(-1) 
        elseif 35 == keycode then   --回车键
                self:Place()
        elseif 23 == keycode then   --delete
            self:Delte()
        elseif 49 == keycode then   --F3载入
            print("载入场景文件")
            self:Load()
        elseif 50 == keycode then   --F4保存
            self:Save()
        end
   end

   local listener = cc.EventListenerKeyboard:create()
   listener:registerScriptHandler(keyboardProcess, cc.Handler.EVENT_KEYBOARD_PRESSED)
   local eventDispatcher = self:getEventDispatcher()
   eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
end

function EditorScene:Place( )
   if self.blockFactory:Hit(self.cur) then
        return
   end

   self.blockFactory:Add(self.curX, self.curY, self.cur.index)
end

function EditorScene:Delte( )
   self.blockFactory:Remove(self.cur)
end

function EditorScene:Save( )
   local file = assert(io.open("scene.lua", "w"))
    file:write("return {\n")
    self.blockFactory:Save(file)

    file:write("}\n")
    file:close()
    print("save ok")
end

function EditorScene:Load()
    local file = assert(dofile("scene.lua"))
    self.blockFactory:Reset()

    for _, t in ipairs(file) do
        self.blockFactory:Add(t.x, t.y, t.index)
    end
    print("load ok")
end

return EditorScene
